package com.puman.watchtrade.fragment.home;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.androidannotations.annotations.res.BooleanRes;

import android.R.bool;
import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.opengl.Visibility;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.adapter.MyPagerAdapter;
import com.puman.watchtrade.fragment.home.adapter.VarietiesRewListViewAdapter;
import com.puman.watchtrade.fragment.home.adapter.VarietiesTodayListViewAdapter;
import com.puman.watchtrade.fragment.home.httphandler.HomeHttpHandler;
import com.puman.watchtrade.fragment.home.model.CustomDigitalClock;
import com.puman.watchtrade.fragment.home.model.Varieties;
import com.puman.watchtrade.util.BaseFragment;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.LoadingProgressDialog;
import com.puman.watchtrade.util.PullDownListView;

/*
 */
@SuppressLint({ "ValidFragment", "NewApi" })
public class VarietiesListFragment extends BaseFragment implements
		OnClickListener,PullDownListView.OnRefreshListioner {
	private View mView;
	private Activity mContext;
	/*
	 * init UI
	 */
	private TextView topTitle;
	private ListView todayListView;
	private ListView reviewListView;
	public ViewPager myViewPager;
	private ImageView cursor;// 动画图片
	PullDownListView mPullDownView1;
	PullDownListView mPullDownView2;

	/*
	 * init variable
	 */
	private String topTitleStr = "";
	private VarietiesTodayListViewAdapter varietiesTodayListViewAdapter;
	private VarietiesRewListViewAdapter varietiesReviewListViewAdapter;
	private Varieties varietiesForToday = new Varieties();
	private Varieties varietiesForReview = new Varieties();
	private List<View> listViews = new ArrayList<View>(); // Tab页面列表

	public static int currIndex = 0;// 当前页卡编号
	private int offset = 0;// 动画图片偏移量
	private int bmpW;// 动画图片宽度
	private String classId = "1";
	private int todayPageNumber = 1;
	private int reviewPageNumber = 1;
	private boolean isRefreash = true;

	public static final int TODAY_SUC = 0x1;
	public static final int TODAY_FAIL = 0x2;
	public static final int REVIEW_SUC = 0x3;
	public static final int REVIEW_FAIL = 0x4;
	public static final int ENDTIME_SUC = 0x5;
	public static final int ENDTIME_FAIL = 0x6;

	private DataResult dataResultForToday = new DataResult();
	private DataResult dataResultForReview = new DataResult();
	private DataResult dataResultForEndTime= new DataResult();
	private HomeHttpHandler homeHttpHandler = new HomeHttpHandler();
	VarietiesListFragment varietiesListFragment;
	private int currentPage = 1;
//	private List<Integer> pageNumList = new ArrayList<Integer>();
	
	public VarietiesListFragment() {
		// TODO Auto-generated constructor stub
	}

	public VarietiesListFragment(String id, String topTitle) {
		this.classId = id;
		this.topTitleStr = topTitle;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	boolean isFirstIn = true;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mContext = getActivity();
		mView = inflater.inflate(R.layout.varieties_layout, container, false);
		varietiesListFragment = this;
		initView();
		getDataToday();
		getDataReview();
		return mView;
	}

	private void initView() {
		mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(this);
		topTitle = (TextView) mView.findViewById(R.id.top_title);
		topTitle.setText(topTitleStr);

		LayoutInflater mInflater = mContext.getLayoutInflater();
		if (isFirstIn) {
			isFirstIn = false;
			listViews.add(mInflater.inflate(R.layout.varieties_list_layout,
					null));
			listViews.add(mInflater.inflate(R.layout.varieties_list_layout,
					null));
			currIndex = 0;
		}
		myViewPager = (ViewPager) mView.findViewById(R.id.myviewpager);
		myViewPager.setAdapter(new MyPagerAdapter(listViews));
		/*******************************/

		myViewPager.setOnPageChangeListener(new MySetOnPageChangeListener());

		cursor = (ImageView) mView.findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(),
				R.drawable.varieties_cursor_left).getWidth();// 获取图片宽度
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		// cursor.setLayoutParams(new LayoutParams(GlobalData.screenWidth/3,
		// LayoutParams.WRAP_CONTENT));
		cursor.setImageMatrix(matrix);// 设置动画初始位置
		cursor.setLayoutParams(new RelativeLayout.LayoutParams(
				GlobalData.screenWidth / 2,
				LinearLayout.LayoutParams.WRAP_CONTENT));
		mView.findViewById(R.id.varieties_today).setOnClickListener(this);
		mView.findViewById(R.id.varieties_review).setOnClickListener(this);
		
//		pageNumList.add(todayPageNumber);
//		pageNumList.add(reviewPageNumber);
		initToday();
		intiReview();

	}

	/*
	 * 初始化今日拍品
	 */
	private void initToday() {
		todayListView = (ListView) listViews.get(0).findViewById(
				R.id.varieties_listview);
		mPullDownView1 = (PullDownListView) listViews.get(0).findViewById(R.id.sreach_list);
		mPullDownView1.setRefreshListioner(this);
		varietiesTodayListViewAdapter = new VarietiesTodayListViewAdapter(
				getActivity(), varietiesForToday);
		todayListView.setAdapter(varietiesTodayListViewAdapter);
		todayListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				// TODO Auto-generated method stub
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				GoodsDetailFragment goodsDetailFragment = new GoodsDetailFragment(
						varietiesForToday.varietiesList.get(position-1)
								.getGoodsNo(), "1", varietiesListFragment);
				transaction.replace(R.id.main_non_bottom, goodsDetailFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
		});
	}

	/*
	 * 初始化回顾
	 */
	private void intiReview() {
		reviewListView = (ListView) listViews.get(1).findViewById(
				R.id.varieties_listview);
		mPullDownView2 = (PullDownListView) listViews.get(1).findViewById(R.id.sreach_list);
		mPullDownView2.setRefreshListioner(this);
		varietiesReviewListViewAdapter = new VarietiesRewListViewAdapter(
				getActivity(), varietiesForReview);
		reviewListView.setAdapter(varietiesReviewListViewAdapter);
		reviewListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				GoodsDetailFragment goodsDetailFragment = new GoodsDetailFragment(
						varietiesForReview.varietiesList.get(position-1)
								.getGoodsNo(), "2", varietiesListFragment);
				transaction.replace(R.id.main_non_bottom, goodsDetailFragment);
				transaction.addToBackStack("varietiesListFragment");
				transaction.commit();
			}
		});
	}
	private LoadingProgressDialog mProgress = null;
	private void getDataToday() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(todayListRunnable);
		
	}
	private void getDataReview() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
		.execute(reviewListRunnable);
	}

	/*
	 * 获取 今日拍品 列表
	 */
	Runnable todayListRunnable = new Runnable() {
		@Override
		public void run() {
			int what = TODAY_FAIL;
			dataResultForToday = homeHttpHandler.VarietiedList("1",
					todayPageNumber + "", classId);
			if (dataResultForToday.flag) {
				what = TODAY_SUC;
			}
			sendMessage(what);
		}
	};

	/*
	 * 获取 拍品回顾 列表
	 */
	Runnable reviewListRunnable = new Runnable() {
		@Override
		public void run() {
			int what = REVIEW_FAIL;
			dataResultForReview = homeHttpHandler.VarietiedList("2",
					reviewPageNumber + "", classId);
			if (dataResultForReview.flag) {
				what = REVIEW_SUC;
			}
			sendMessage(what);
		}
	};
	
	private void getEndTime(){
		MainActivity.getInstant().cachedThreadPoolMinPriority
		.execute(endTimeRunnable);
	}
	
	/*
	 * 获取 结束时间
	 */
	Runnable endTimeRunnable = new Runnable() {
		@Override
		public void run() {
			int what = ENDTIME_FAIL;
			dataResultForEndTime = homeHttpHandler.endTime(classId);
			if (dataResultForEndTime.flag) {
				what = ENDTIME_SUC;
			}
			sendMessage(what);
		}
	};

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			Gjfun.stopProgressDialog(mProgress);
			switch (msg.what) {
			case TODAY_SUC:
				mPullDownView1.onRefreshComplete();
				mPullDownView1.onLoadMoreComplete();
				if (((Varieties) (dataResultForToday.object)).varietiesList
						.size() == 0) {
					if (todayPageNumber -1 == 1) {
						todayPageNumber = 1;
					}else {
						todayPageNumber--;
					}
				}
				if (isRefreash) {
					varietiesForToday.varietiesList.clear();
				}else {
				}
				for (int i = 0; i < ((Varieties) (dataResultForToday.object)).varietiesList
						.size(); i++) {
					varietiesForToday.varietiesList
							.add(((Varieties) (dataResultForToday.object)).varietiesList
									.get(i));
				}
				if (varietiesForToday.varietiesList.size() == 0) {
					getEndTime();
//					Gjfun.emptyLayout(listViews.get(0), "商品即将上架", "", true);
				}else {
					if (varietiesForToday.varietiesList.size() <5) {
						mPullDownView1.setMore(false);
					}else {
						mPullDownView1.setMore(true);
					}
					emptyLayout(listViews.get(0), null, "", false);
				}
				varietiesTodayListViewAdapter.notifyDataSetChanged();
				break;
			case TODAY_FAIL:
				mPullDownView1.onRefreshComplete();
				mPullDownView1.onLoadMoreComplete();
				emptyLayout(listViews.get(0), "商品即将上架", "", true);
				break;
			case REVIEW_SUC:
				mPullDownView2.onRefreshComplete();
				mPullDownView2.onLoadMoreComplete();
				if (((Varieties) (dataResultForReview.object)).varietiesList
						.size() == 0) {
					if (reviewPageNumber -1 == 1) {
						reviewPageNumber = 1;
					}else {
						reviewPageNumber--;
					}
				}
//				Log.i("curry", "isRefreash:"+isRefreash);
				if (isRefreash) {
					varietiesForReview.varietiesList.clear();
				}else {
					
				}
				for (int i = 0; i < ((Varieties) (dataResultForReview.object)).varietiesList
						.size(); i++) {
					varietiesForReview.varietiesList
							.add(((Varieties) (dataResultForReview.object)).varietiesList
									.get(i));
				}
				if (varietiesForReview.varietiesList.size() == 0) {
					emptyLayout(listViews.get(1), "本周暂时木有商品", "", true);
				}else {
					if (varietiesForReview.varietiesList.size() < 5) {
						mPullDownView2.setMore(false);
					}else {
						mPullDownView2.setMore(true);
					}
					emptyLayout(listViews.get(1), null, "", false);
				}
				varietiesReviewListViewAdapter.notifyDataSetChanged();
				break;
			case REVIEW_FAIL:
				mPullDownView2.onRefreshComplete();
				mPullDownView2.onLoadMoreComplete();
				emptyLayout(listViews.get(1), "本周暂时木有商品", "", true);
				break;
			case ENDTIME_SUC:
				Log.i("curry", dataResultForEndTime.object+"");
				if(!dataResultForEndTime.object.toString().equals("")){
						emptyLayout(listViews.get(0), "商品即将上架", dataResultForEndTime.object.toString(), true);
				}else{
					emptyLayout(listViews.get(0), "商品即将上架", "", true);
				}
				break;
			case ENDTIME_FAIL:
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.main_left_imgbtn:
			MainActivity.getInstant().fragmentManager.popBackStack();
			break;
		case R.id.varieties_today:
			myViewPager.setCurrentItem(0);
			break;
		case R.id.varieties_review:
			myViewPager.setCurrentItem(1);
			break;
		default:
			break;
		}

	}

	/**
	 * ViewPager页面选项卡切换监听器
	 */
	class MySetOnPageChangeListener implements OnPageChangeListener {

		public void onPageScrollStateChanged(int arg0) {
		}

		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		public void onPageSelected(int position) {
			DisplayMetrics dm = new DisplayMetrics();
			mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
			int screenW = dm.widthPixels;// 获取分辨率宽度
			int one = screenW / 2;
			int two = one * 2;// 页卡1 -> 页卡3 偏移量
			Animation animation = null;
//			Log.i("curry", "postion:"+position);
//			Log.i("curry", "currIndex:"+currIndex);
			switch (position) {
			case 0:
				cursor.setImageDrawable(MainActivity.getInstant().getResources().getDrawable(R.drawable.varieties_cursor_left));
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(two, 0, 0, 0);
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(0, one, 0, 0);
					cursor.setImageDrawable(MainActivity.getInstant().getResources().getDrawable(R.drawable.varieties_cursor_right));
				} else if (currIndex == 2) {
					animation = new TranslateAnimation(one, two, 0, 0);
				}
				else if (currIndex == 1) {
					animation = new TranslateAnimation(one, one, 0, 0);
					cursor.setImageDrawable(MainActivity.getInstant().getResources().getDrawable(R.drawable.varieties_cursor_right));
				}
				break;
			default:

				break;
			}
			if (currIndex == 1) {
				animation = new TranslateAnimation(one, 0, 0, 0);
				cursor.setImageDrawable(MainActivity.getInstant().getResources().getDrawable(R.drawable.varieties_cursor_left));
			} else if (currIndex == 2) {
				animation = new TranslateAnimation(two, 0, 0, 0);
				cursor.setImageDrawable(MainActivity.getInstant().getResources().getDrawable(R.drawable.varieties_cursor_left));
			}
			currIndex = position;
//			mView.findViewById(R.id.myviewpager).startAnimation(MainActivity.animationalpha);
//			Toast.makeText(MainActivity.getInstant(), "currIndex:"+currIndex, Toast.LENGTH_SHORT).show();
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		isRefreash = true;
		if (currIndex == 0) {
			todayPageNumber = 1;
			getDataToday();
//			Toast.makeText(MainActivity.getInstant(), "1", Toast.LENGTH_SHORT).show();
		}else {
			reviewPageNumber = 1;
			getDataReview();
//			Toast.makeText(MainActivity.getInstant(), "2", Toast.LENGTH_SHORT).show();
		}
		
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		isRefreash = false;
		if (currIndex == 0) {//第一页
			Log.i("curry", "getDataToday:onLoadMore");
			todayPageNumber = todayPageNumber+1;
			getDataToday();
//			Toast.makeText(MainActivity.getInstant(), "1", Toast.LENGTH_SHORT).show();
		}else {//第二页
			Log.i("curry", "getDataReview:onLoadMore");
			reviewPageNumber = reviewPageNumber+1;
			getDataReview();
//			Toast.makeText(MainActivity.getInstant(), "2", Toast.LENGTH_SHORT).show();
		}
	}

	private void caculateTime() {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

		try {
			Date d1 = df.parse("2015-08-25 18:40:00");
			Date d2 = new Date(System.currentTimeMillis());// 你也可以获取当前时间
			long diff = d1.getTime() - d2.getTime();// 这样得到的差值是微秒级别
			long days = diff / (1000 * 60 * 60 * 24);
			long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
			long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours
					* (1000 * 60 * 60))
					/ (1000 * 60);

//			System.out.println("" + days + "天" + hours + "小时" + minutes + "分");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// Date d2 = df.parse("2006-07-02 11:20:00");

	
	}
	
	/**
	 * 数据为空时的默认布局 curry 201506
	 * 
	 * @param mView
	 *            当前界面
	 * @param info
	 *            提示信息
	 * @param isShow
	 *            是否显示
	 */
	 Random random = new Random();
	public  void emptyLayout(View mView, String info, String endtime,
			boolean isShow) {
		CustomDigitalClock clock;
		clock = (CustomDigitalClock) mView
				.findViewById(R.id.load_default_time);
		if (isShow) {
			mView.findViewById(R.id.load_empty_layout_info).setVisibility(
					View.VISIBLE);
			if (null != info) {
				((TextView) mView.findViewById(R.id.load_default_info))
						.setText(info);
				if (!endtime.equals("")) {
					DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					try {
						Date d1 = df.parse(endtime);
						clock.setEndTime(d1.getTime());
						clock.setClockListener(new CustomDigitalClock.ClockListener() { // register
							@Override
							public void timeEnd() {
								// The clock time is ended.
							}

							@Override
							public void remainFiveMinutes() {
								// The clock time is remain five minutes.
							}
						});
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}else{
					clock.setVisibility(View.GONE);
				}
			}
		} else {
			mView.findViewById(R.id.load_empty_layout_info).setVisibility(
					View.GONE);
		}
	}
}
